package com.sskj.jd.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sskj.core.exception.MException;
import com.sskj.dingtalk.exception.OApiException;
import com.sskj.dingtalk.service.impl.DingTalkMessageServiceImpl;
import com.sskj.dingtalk.utils.CalendarUtil;
import com.sskj.dingtalk.utils.CodingUtil;
import com.sskj.dingtalk.utils.HttpHelper;
import com.sskj.dingtalk.vo.TiXingRenWuNeiRongVO;
import com.sskj.jd.domain.entity.FoundWT;
import com.sskj.jd.domain.entity.JianDuJiLuCJJG;
import com.sskj.jd.domain.entity.JianDuJiLuRenYuan;
import com.sskj.jd.domain.entity.WenTiFILE;
import com.sskj.jd.domain.entity.WenTiIMG;
import com.sskj.jd.domain.entity.WenTiLX;
import com.sskj.jd.domain.entity.AnQuanZGTZS;
import com.sskj.jd.repository.AnQuanZGTZSRepostiory;
import com.sskj.jd.repository.EmployeeForRepository;
import com.sskj.jd.trans.AnQuanZGTZSTrans;
import com.sskj.jd.vo.AnQuanZGTZSVO;
import com.sskj.personnel.domain.entity.EmployeeEntity;
import com.sskj.personnel.repository.EmployeeRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/jd/aqzgtzs", method = { RequestMethod.POST, RequestMethod.GET })
@Transactional
@Api(value = "安全整改通知书", description = "安全整改通知书")
public class AnQuanZGTZSServiceImpl {

	protected final Log logger = LogFactory.getLog(AnQuanZGTZSServiceImpl.class);

	@Value("${sskj.conf.restUrl}")
	private String restUrl;

	@Autowired
	AnQuanZGTZSRepostiory aqRepository;

	@Autowired
	EmployeeRepository employeeRepository;
	
	@Autowired
	EmployeeForRepository employeeForRepository;		

	@Autowired
	DingTalkMessageServiceImpl dingTalkMessageServiceImpl;

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/save", method = { RequestMethod.POST })
	@ApiOperation(value = "新增安全整改通知书", notes = "新增安全整改通知书", httpMethod = "POST")
	public void save(@RequestBody AnQuanZGTZS aqtzs) throws MException {

		AnQuanZGTZS oldAnQuanZGTZS = null;

		try {

			if (aqtzs.getId() != null) {
				oldAnQuanZGTZS = aqRepository.get(aqtzs.getId());
			}

			if (oldAnQuanZGTZS == null) {
				String cdlike = "宜市建安监[" + CalendarUtil.getYearyyyy(Calendar.getInstance()) + "ZG%]号";
				String maxCode = aqRepository.maxCode(cdlike, 30);
				String coding = CodingUtil.getMaxIDQuery(maxCode, cdlike, 18);
				aqtzs.setCoding(coding);
				aqtzs.getEng().setOid(aqtzs.getEng().getId());
				aqtzs.getEng().setId(null);

			}
			aqtzs.setJllxName("安全问题整改通知书"); 
			for (JianDuJiLuRenYuan jdry : aqtzs.getJdrys()) {
				EmployeeEntity emp = employeeRepository.findByDD_Id(jdry.getEmplId());
				if (emp != null) {
					jdry.setUserId(emp.getResteasy_emp_id());
				}
				else
				{
					EmployeeEntity emp2 = employeeForRepository.findByName(jdry.getName());
					if (emp2 != null) {
						jdry.setEmplId(emp2.getDdId());
						jdry.setName(emp2.getName());					
						jdry.setUserId(emp2.getResteasy_emp_id());
					}				 
				}
				jdry.setJdjl(aqtzs);
				jdry.setCreatorId(aqtzs.getCreatorId());	
			}

			for (JianDuJiLuCJJG cjjg : aqtzs.getCjjgs()) {
				cjjg.setJdjl(aqtzs);
				cjjg.setCreatorId(aqtzs.getCreatorId());

			}

			for (FoundWT wt : aqtzs.getWt()) {
				wt.setJdjl(aqtzs);

				for (WenTiFILE file : wt.getFiles()) {
					file.setWt(wt);
					file.setCreatorId(aqtzs.getCreatorId());
				}

				for (WenTiIMG img : wt.getImages()) {
					img.setWt(wt);
					img.setCreatorId(aqtzs.getCreatorId());
				}

				for (WenTiLX lx : wt.getWtlx()) {
					lx.setWt(wt);
					lx.setCreatorId(aqtzs.getCreatorId());
				}
			}
			aqRepository.save(aqtzs);

		} catch (Exception e) {
			e.printStackTrace();
			throw new MException("system_error");

		}

	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/upload", method = { RequestMethod.POST })
	@ApiOperation(value = "上传安全整改通知书", notes = "上传安全整改通知书", httpMethod = "POST")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "安全整改通知书 IDS", paramType = "form", required = true, dataType = "string") })
	public void upload(String id) throws MException {

		AnQuanZGTZS oldAnQuanZGTZS = aqRepository.get(id);
		try {

			oldAnQuanZGTZS.setIsUpload(true);
			TiXingRenWuNeiRongVO tx = upload(oldAnQuanZGTZS);
			dingTalkMessageServiceImpl.sendOAMessage(dingTalkMessageServiceImpl.reNextShenHeMessage(tx));

		} catch (OApiException e) {
			e.printStackTrace();

			Object[] msg = { e.getMessage() };
			throw new MException("custom_msg", msg);

		}
		aqRepository.save(oldAnQuanZGTZS);

	}

	// 同步往监督系统
	public TiXingRenWuNeiRongVO upload(AnQuanZGTZS aqtzs) throws OApiException {

		AnQuanZGTZSTrans trans = new AnQuanZGTZSTrans(aqtzs);
		AnQuanZGTZSVO vo = trans.returnVO();
		EmployeeEntity emp = employeeRepository.findByDD_Id(aqtzs.getCreatorId());
		if (emp != null) {
			vo.setCreateId(emp.getResteasy_emp_id());
		}
		JSONObject obj = HttpHelper.httpPost(restUrl + "dingtalk/jd/aqzgtzs/up", vo);

		if (null == obj) {
			throw new OApiException(1, "");
		} else {
			return JSON.parseObject(obj.getString("result"), TiXingRenWuNeiRongVO.class);
		}

	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/get", method = { RequestMethod.POST })
	@ApiImplicitParams({ @ApiImplicitParam(name = "spId", value = "记录ID", paramType = "form", dataType = "string") })
	@ApiOperation(value = "获取安全整改通知书", notes = "获取安全整改通知书", httpMethod = "GET")
	public AnQuanZGTZS get(String spId) throws Exception {

		AnQuanZGTZS aqtzs = aqRepository.findOneById(spId);
		return aqtzs;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/del", method = { RequestMethod.POST, RequestMethod.DELETE })
	@ApiOperation(value = "删除安全整改通知书", notes = "删除安全整改通知书  多个安全整改通知书ID用,号分隔", httpMethod = "DELETE")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "安全整改通知书 IDS", paramType = "form", required = true, dataType = "string") })
	public void del(String id) {
		if (StringUtils.isNotEmpty(id)) {
			String[] idsArr = id.split(",");
			List<String> list = new ArrayList<String>();

			if (idsArr != null) {
				for (String idd : idsArr) {
					if (!idd.equals("ADMIN")) {
						list.add(idd);
					}
				}
				aqRepository.delete(list);
			}
		}

	}

}
